<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';

import { computed, onMounted, reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { Apis } from '#/api';
import { DICT_TYPE, dictUtils } from '#/utils/dict';

const emit = defineEmits(['success']);

export interface EditRoleModalState {
  isUpdate: boolean;
  record: any;
}
type ModalState = EditRoleModalState;

const data = ref<ModalState>({
  isUpdate: false,
  record: {},
});

let dictMap = reactive<any>({});

let form = reactive({
  parentId: '',
  name: '',
  code: '',
  status: 0,
  sort: 0,
  isDefault: false,
  remark: '',
});

const formRef = ref<FormInstance>();

const isLoading = ref(false);

const roleList = ref<any>([]);
const parentRoleList = computed(() => {
  let data = [{ name: '无', code: '0' }];
  data = [
    ...data,
    ...roleList.value.filter((item) => !item.parentId || item.parentId === '0'),
  ];
  return data.map((item) => ({
    label: item.name,
    value: item.code,
  }));
});

const rules: Record<string, Rule[]> = {
  parentId: [{ required: true, message: '请选择父级角色' }],
  name: [{ required: true, message: '请填写角色名称' }],
  code: [{ required: true, message: '请填写角色编码' }],
};

const [BaseModal, baseModalApi] = useVbenModal({
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      data.value = baseModalApi.getData<ModalState>();

      const res = await Apis.system.role.getList();
      roleList.value = res.list;

      if (data.value.record) {
        form = data.value.record as any;
      }
      initForm();
    }
  },
  onConfirm: onSubmit,
});

async function onSubmit() {
  await formRef.value!.validate();

  try {
    isLoading.value = true;

    message.success({
      content: `操作成功`,
    });

    baseModalApi.close();
    emit('success');
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    isLoading.value = false;
  }
}

function initForm() {
  const defaultStatus = dictUtils.getDictDefaultObjByOptions(
    dictMap[DICT_TYPE.sysCommonStatus],
  )?.value;
  form.status = form.status ?? defaultStatus;

  const defaultWhether = dictUtils.getDictDefaultObjByOptions(
    dictMap[DICT_TYPE.sysCommonWhether],
  )?.value;
  form.isDefault = form.isDefault ?? defaultWhether;

  form.parentId = form.parentId ?? parentRoleList.value[0]?.value;
}

onMounted(async () => {
  dictMap = await dictUtils.getDictDatasAsync([
    { type: DICT_TYPE.sysCommonStatus, valueType: 'number' },
    { type: DICT_TYPE.sysCommonWhether, valueType: 'number' },
  ]);

  initForm();
});
</script>
<template>
  <BaseModal
    :confirm-loading="isLoading"
    :title="data.isUpdate ? '修改角色' : '新增角色'"
    class="w-[600px]"
  >
    <a-form
      ref="formRef"
      :label-col="{ style: 'width: 120px' }"
      :model="form"
      :rules="rules"
      class="grid-cols-1"
      label-class="w-full"
      layout="horizontal"
    >
      <a-form-item label="父级角色" name="parentId">
        <a-select
          v-model:value="form.parentId"
          :options="parentRoleList"
          class="w-full"
          placeholder="请选择父级角色"
        />
      </a-form-item>

      <a-form-item label="角色名称" name="name">
        <a-input
          v-model:value="form.name"
          class="w-full"
          max-length="50"
          placeholder="请填写角色名称"
        />
      </a-form-item>

      <a-form-item label="角色编码" name="code">
        <a-input
          v-model:value="form.code"
          class="w-full"
          max-length="50"
          placeholder="请填写角色编码"
        />
      </a-form-item>

      <a-form-item label="记录状态" name="status">
        <a-radio-group
          v-model:value="form.status"
          :options="dictMap[DICT_TYPE.sysCommonStatus]"
          class="w-full"
        />
      </a-form-item>

      <a-form-item label="排序" name="sort">
        <a-input
          v-model:value="form.sort"
          class="w-full"
          max-length="50"
          placeholder="请填写排序"
        />
      </a-form-item>

      <a-form-item label="备注" name="remark">
        <a-textarea
          v-model:value="form.remark"
          :auto-size="{ minRows: 3, maxRows: 5 }"
          class="w-full"
          max-length="200"
          placeholder="请填写备注"
        />
      </a-form-item>
    </a-form>
  </BaseModal>
</template>
